<template>
  <div>
    <a-row :gutter="10">
      <a-col span="18">
        <a-row :gutter="10">
          <a-col span="6">
            <div style="">
              <div style="background: #ffffff;display: flex;height:120px;align-items: center;justify-content: space-around">
                <img  src="~@assets/111.png" height="75"/>
                <div>
                  <p style="font-size:18px;font-weight: 550;margin-bottom:12px">
                    <span style="color: #b2b2b2">{{timeFix}}！</span>
                    <span v-if="userInfo">{{userInfo.realname}}</span>
                  </p>
                  <p style="color: #b2b2b2;font-size:14px;margin-bottom:0">{{timeWh}}</p>
                </div>
              </div>
              <div style="margin-top:10px;height:120px;background: #ffffff;display: flex;flex-direction: column;justify-content: center">
                <p style="padding-left:24px;color: #b2b2b2;font-size:18px;font-weight: 550;margin-bottom:12px"><a-icon style="margin-right:8px" type="cluster" />部门：<span style="color:#0B82C6">{{currDepartName}}</span>
                  </p>
                <p style="padding-left:24px;color: #b2b2b2;font-size:18px;font-weight: 550;margin-bottom:0"><a-icon style="margin-right:8px" type="phone" />电话：<span style="color:#0B82C6">{{userInfo?.phone}}</span></p>
              </div>
          </div></a-col>
          <a-col span="18">
            <a-card :loadding="loading" :bordered="false" style="height:250px" :headStyle="{padding:'0 8px'}">
              <span slot="title" style="font-size:14px;font-weight:550;border-left:8px solid #0B82C6;padding-left:8px">快捷入口</span>
               <a-icon type="setting" slot="extra" @click="settingQE"></a-icon>
            <div style="display: flex;flex-wrap: wrap;height:160px;overflow-y:auto">
                 <!-- <draggable  v-model="qeList" @end="onEnd" > -->
                  <div v-for="(item, index) in qeList" :key="item.id" class="q-item" @click="()=>{$router.push({path:item.path})}" >
                    <img :src="require('@/assets/'+index%4+'.png')" height="40" width="40"/>
                    <p>{{item.meta?.title??''}}</p>
                  </div>

                 <!-- </draggable> -->
            </div>
            </a-card>
          </a-col>
          <a-col span="24" style="margin-top:10px;">
            <a-card style="height:640px" :bordered="false" :bodyStyle="{height:'559px',padding:'8px 8px 8px 8px'}" :headStyle="{padding:'0 8px'}">
                <span slot="title" style="font-size:14px;font-weight:550;border-left:8px solid #0B82C6;padding-left:8px">待办任务</span>
                <indextable class="emptablerow"></indextable>
            </a-card>
          </a-col>
        </a-row>
      </a-col>
      <a-col span="6">
        <a-card :bodyStyle="{padding:'0 12px 12px 12px'}" :headStyle="{padding:'0 8px'}" :bordered="false" style="height:900px;">
          <span slot="title" style="font-size:14px;font-weight:550;border-left:8px solid #0B82C6;padding-left:8px">消息中心</span>
          <a slot="extra">标记已读</a>
          <a-tabs>
            <a-tab-pane tab="未读" key="0">
              <template v-if="announcement1.length>0">
                <div style="height:820px;overflow-y:auto;">
                  <template v-for="(item,index) in announcement1">
                    <div style="padding:0 8px;background:#f1f4f9;display:flex;justify-content: space-between;align-items: center;margin-bottom:8px">
                      <div style="display:flex">
                        <div style="margin-top:6px;border-radius: 50%;width: 10px;height:10px;background: #0b81c5;margin-right:4px"></div>
                        <div>
                          <p style="margin-bottom:8px">{{item.titile}}</p>
                          <p style="color:#b2b2b2">{{item.sendTime}}</p>
                        </div>
                      </div>
                      <div style="color:#b2b2b2">{{msgCategoryList[item.msgCategory]}}</div>
                    </div>
                  </template>
                </div>
              </template>
             <template v-else>
               <a-empty></a-empty>
             </template>
            </a-tab-pane>
            <a-tab-pane tab="已读" key="1">
              <template v-if="announcement2.length>0">
                <div style="height:820px;overflow-y:auto;">
                  <template v-for="(item,index) in announcement2">
                    <div style="padding:0 8px;background:#f1f4f9;display:flex;justify-content: space-between;align-items: center;margin-bottom:8px">
                      <div style="display:flex">
                        <div style="margin-top:6px;border-radius: 50%;width: 10px;height:10px;background: #0b81c5;margin-right:4px"></div>
                        <div>
                          <p style="margin-bottom:8px">{{item.titile}}</p>
                          <p style="color:#b2b2b2">{{item.sendTime}}</p>
                        </div>
                      </div>
                      <div style="color:#b2b2b2">{{msgCategoryList[item.msgCategory]}}</div>
                    </div>
                  </template>
                </div>
              </template>
              <template v-else>
                <a-empty></a-empty>
              </template>
            </a-tab-pane>
          </a-tabs>
        </a-card>
      </a-col>
    </a-row>
<!--/*<img src="~@assets/首页.png" style="width:100%">*/-->
    <a-modal @cancel="()=>{this.visable=false}"  @ok="handleSubmit" destroyOnClose :width="600" :visible="visable" title="配置快捷入口">
       <a-table
          ref="table"
          size="middle"
          :scroll="{x:true}"
          bordered
          rowKey="id"
          :columns="columns"
          :dataSource="pList"
          :pagination="ipagination"
          :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange , type: 'checkbox'}"
          class="j-table-force-nowrap1"

          />

    </a-modal>
  </div>
</template>

<script>
  // import draggable from "vuedraggable";
  import indextable from "@/views/flowable/task/todo/indextable"
  import {timeFix, whnm} from "@/utils/util";
  import {mapGetters, mapState} from "vuex";
  import store from '@/store/'
  import {getAction} from "@api/manage";
  import { postAction } from '../../api/manage';
  export default {
    name: "Analysis",
    components:{
      indextable,
      // draggable
    },
    data() {
      return {
        loading:false,
        qeList:[],
        pList:[],
        userInfo: {
          id: '',
          realname: '',
          phone: ''
        },
        ipagination: {
            pageSize: 20,
          },
         columns: [
          {
            title: '#',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: "center",
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }
          },
          {
            title: '名称',
            align: "center",
            dataIndex: 'meta.title',
             scopedSlots: { customRender: 'title' }
          },
           {
            title: '地址',
            align: "center",
            dataIndex: 'path'
          },
         ],
        visable:false,
        msgCategoryList:['未分类','通知公告','系统消息','待办消息'],
        timeFix: timeFix(),
        timeWh:whnm(),
         selectedRowKeys: [],
      /* table选中records*/
      selectionRows: [],
      qeid:null,
        url:{
          list: '/sys/sysAnnouncementSend/getMyAnnouncementSend',
        },
        announcement1:[],
        announcement2:[],
        currDepartName:'',
      }
    },
    computed: {
      ...mapState({
        // 后台菜单
        permissionMenuList: state => state.user.permissionList,
        userInfo: state => state.user.info // 直接映射用户信息

      })
    },
    created() {
      console.log(this.permissionMenuList)
      this.pList = this.treeToList(this.permissionMenuList)

      // 确保用户信息已从 store 中获取
      this.userInfo = store.getters.userInfo || {}

      // 使用 $nextTick 确保在下一个 DOM 更新周期执行
      this.$nextTick(() => {
        if (this.userInfo && this.userInfo.id) {
          this.getQEList()
          this.getSysMes()
          this.loadDepartList()
        } else {
          console.warn('用户信息未加载，部分功能可能不可用')
        }
      })
    },
    methods: {
      ...mapGetters(["nickname"]),
    // onEnd() {
    //   this.selectionRows=JSON.parse(JSON.stringify(this.qeList))
    //   this.selectedRowKeys=this.selectionRows.map(e=>e.id)
    //   this.handleSubmit()
    // },

      getQEList() {
        // 获取配置
        this.qeList = []

        // 添加安全检查
        if (!this.userInfo || !this.userInfo.id) {
          console.warn('用户ID不存在，无法获取快捷入口')
          return
        }

        getAction('/kjrk/kuaijierukou/list', {user: this.userInfo.id, pageSize: -1})
          .then(res => {
            console.log("getQEList", res)
            if (res && res.result) {
              this.qeid = res.result.records?.[0]?.id ?? null
              this.selectedRowKeys = res.result.records?.[0]?.qeids?.split(',') ?? []

              // 安全地添加到 qeList
              this.selectedRowKeys.forEach(e => {
                const found = this.pList.find(e1 => e1.id == e)
                if (found) {
                  this.qeList.push(found)
                }
              })
            }
          })
          .catch(err => {
            console.error('获取快捷入口失败', err)
          })
      },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectionRows = selectionRows;
      console.log(this.selectedRowKeys)

    },
      settingQE(){
          this.visable=true

      },
      handleSubmit(){
        this.loading=true
      // 保存配置
          this.qeList=JSON.parse(JSON.stringify(this.selectionRows))
          this.visable=false
          if(this.qeid){
 postAction('/kjrk/kuaijierukou/edit',{id:this.qeid,user:this.userInfo.id,qeids:this.selectedRowKeys.join(',')}).then(res=>{
             this.loading=false

          })
          }else{
 postAction('/kjrk/kuaijierukou/add',{user:this.userInfo.id,qeids:this.selectedRowKeys.join(',')}).then(res=>{
            this.loading=false

          })
          }

      },

     treeToList(tree, list = []) {
        for (const node of tree) {
          const { children, ...rest } = node;
          list.push({ ...rest });

          if (children && children.length > 0) {
            this.treeToList(children, list);
          }
        }
        return list;
      },


      loadDepartList(){
        return new Promise(resolve => {
          let url = "/sys/user/getCurrentUserDeparts"
          this.currDepartName=''
          getAction(url).then(res=>{
            if(res.success){
              let departs = res.result.list
              let orgCode = res.result.orgCode
              if(departs && departs.length>0){
                for(let i of departs){
                  if(i.orgCode == orgCode){
                    this.currDepartName = i.departName
                    break
                  }
                }
              }

            }
            resolve()
          })
        })
      },
      getSysMes(){
        // 获取系统消息
        getAction(this.url.list).then((res) => {
          if (res.success) {
            this.announcement1 = res.result.records.filter(e=>e.readFlag==0);
            this.announcement2 = res.result.records.filter(e=>e.readFlag==1);

          }
        }).catch(error => {
        });
      }
    }
  }
</script>
<style scoped>
.emptablerow ::v-deep .ant-table-tbody tr:nth-child(2n)
{
  background-color: #f1f4f9;
}
.q-item{
  width: 90px;
  margin-right: 10px;
  text-align:center;
  cursor: pointer;
}
</style>